import 'dart:ui';
import 'package:canteen/class/dish.dart';
import 'package:canteen/constants.dart';
import 'package:canteen/edit_c_v.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:canteen/page/edit_menu_page.dart';
import 'package:flutter/material.dart';
import 'package:vibration/vibration.dart';
import 'package:canteen/component/dish_widget.dart';
import 'package:canteen/component/category_widget.dart';
import 'package:canteen/menu_c_v.dart';

import '../class/set_meal.dart';

class MenuPage extends StatefulWidget {
  static const String id = 'menu_page';

  @override
  State<MenuPage> createState() => _MenuPageState();
}

class _MenuPageState extends State<MenuPage> {
  //TODO:限制员工进入
  late List<String> categories;
  int active = 0;
  String searchQuery = '';
  late Map<String, List<String>> dishes;

  void refresh({isAdd, index, isCategory = false}) {
    if (isCategory) {
      if (isAdd) {
        name = '';
        return;
      }
      name = categories[index];
    } else {
      name = '';
      ingredientString = '';
      category = categories[active];
      if (!isAdd) {
        getDorI(index);
      } else {
        dish = Dish(name: name, components: {}, category: category);
        setMeal = SetMeal(dishes: {}, name: name, category: category);
      }
    }
  }

  void getDorI(index) {
    name = getFilteredDishes()[index];
    type = findSetMealByName(name, allSetMeals) != null ? '套餐' : '单品';
    bool isDish = type == '单品' ? true : false;
    List<String> tempR = [];
    if (!isDish) {
      setMeal = findSetMealByName(name, allSetMeals)!;
      setMeal.dishes.forEach((key, value) {
        tempR.add('${key.name} $value');
      });
    } else {
      dish = findDishByName(name, allDishes)!;
      dish.components.forEach((key, value) {
        tempR.add('${key.type} ${key.name} ${value} ${key.unit}');
      });
    }
    ingredientString = tempR.join('#');
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getCategories();
    getDishes();
  }

  void getDishes() {
    dishes = {};
    dishesWithCategory.forEach((key, value) {
      dishes.addEntries([MapEntry(key, value.map((e) => e.name).toList())]);
    });
    setMealsWithCategory.forEach((key, value) {
      dishes[key]?.addAll([...value.map((e) => e.name)]);
    });
    dishes.map((key, value) => MapEntry(key, value.add('添加菜品')));
  }

  void getCategories() {
    categories = [...sortedCategory];
    categories.add('添加');
  }

  void triggerVibration() async {
    // 检查设备是否支持震动
    bool canVibrate = await Vibration.hasVibrator() ?? false;
    if (canVibrate) {
      // 触发一次短震动
      Vibration.vibrate(duration: 100);
    }
  }

  List<String> getFilteredDishes() {
    if (searchQuery.isEmpty) {
      return dishes[categories[active]] ?? [];
    }
    return dishes[categories[active]]
            ?.where((dish) =>
                dish.toLowerCase().contains(searchQuery.toLowerCase()))
            .toList() ??
        [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffbfbfb),
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          '编辑菜单',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
      ),
      body: Column(
        children: [
          Container(
            margin: EdgeInsets.only(left: 20, right: 20, bottom: 10,top: 10),
            padding: EdgeInsets.symmetric(horizontal: 15),
            height: 46,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              border: Border.all(color: Colors.black),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.search_rounded,
                ),
                Expanded(
                  child: TextField(
                    onChanged: (value) {
                      setState(() {
                        searchQuery = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: '搜索菜品',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Stack(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        clipBehavior: Clip.hardEdge,
                        decoration: BoxDecoration(
                            color: Color(0XFFffffff),
                            borderRadius: active == 0
                                ? BorderRadius.only(
                                    topLeft: Radius.circular(25),
                                    bottomLeft: Radius.circular(25),
                                    bottomRight: Radius.circular(25))
                                : BorderRadius.circular(25)),
                        child: ListView.builder(
                          itemCount: categories.length,
                          itemBuilder: (context, index) {
                            return CategoryWidget(
                              longPress: () {
                                refresh(
                                    isAdd: false,
                                    isCategory: true,
                                    index: index);
                                Navigator.pushNamed(
                                    context, EditMenuPage.id, arguments: {
                                  'isCategory': true,
                                  'isAdd': false
                                }).then((value) {
                                  setState(() {
                                    getDishes();
                                    getCategories();
                                  });
                                });
                                triggerVibration();
                              },
                              onClick: () {
                                if (categories[index] == '添加') {
                                  refresh(isAdd: true, isCategory: true);
                                  Navigator.pushNamed(
                                          context, EditMenuPage.id,
                                          arguments: {'isCategory': true})
                                      .then((value) {
                                    setState(() {
                                      getDishes();
                                      getCategories();
                                    });
                                  });
                                  return;
                                }
                                setState(() {
                                  active = index;
                                });
                              },
                              active: active,
                              activeNum: index,
                              category: categories[index],
                            );
                          },
                        ),
                      ),
                    ),
                    Expanded(
                      flex: menuFlex,
                      child: Container(
                        margin: EdgeInsets.only(right: 20),
                        decoration: BoxDecoration(
                          border: Border.all(
                              color: Colors.black.withOpacity(0.5),
                              width: 2),
                          borderRadius: active == 0
                              ? BorderRadius.only(
                                  topRight: Radius.circular(25),
                                  bottomLeft: Radius.circular(25),
                                  bottomRight: Radius.circular(25))
                              : BorderRadius.circular(25),
                          color: Color(0XFFffffff),
                        ),
                        child: AnimatedSwitcher(
                          duration: Duration(milliseconds: 250),
                          child: ListView.builder(
                            key: ValueKey(active),
                            itemCount: getFilteredDishes().length,
                            itemBuilder: (context, index) {
                              return DishWidget(
                                onTap: () {
                                  if (dishes[categories[active]]?[index] ==
                                      '添加菜品') {
                                    refresh(isAdd: true);
                                    Navigator.pushNamed(
                                      context,
                                      EditMenuPage.id,
                                    ).then((value) {
                                      setState(() {
                                        getDishes();
                                        getCategories();
                                      });
                                    });
                                  } else {
                                    refresh(isAdd: false, index: index);
                                    Navigator.pushNamed(
                                            context, EditMenuPage.id,
                                            arguments: {'isAdd': false})
                                        .then((value) {
                                      setState(() {
                                        getDishes();
                                        getCategories();
                                      });
                                    });
                                  }
                                },
                                dishName: getFilteredDishes()[index],
                                childWidget: dishes[categories[active]]
                                            ?[index] ==
                                        '添加菜品'
                                    ? Icon(
                                        Icons.add_circle_outline_rounded,
                                        size: 30,
                                      )
                                    : Icon(Icons.arrow_forward_ios_rounded),
                              );
                            },
                          ),
                        ),
                      ),
                    )
                  ],
                ),
                Positioned(
                  left: MediaQuery.of(context).size.width * 1 / (menuFlex+1) - 2,
                  top: active * cWHeight + 2,
                  child: Container(
                    width: 4,
                    height: cWHeight-4,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 20,
          )
        ],
      ),
    );
  }
}
